package cn.bdqn.service.impl;

import cn.bdqn.config.shiro.MyRealm;
import cn.bdqn.mapper.UserMapper;
import cn.bdqn.pojo.User;
import cn.bdqn.service.UserService;
import cn.bdqn.utils.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;

    @Override
    public User getUserByUsrName(String usrName) {
        return userMapper.getUserByUsrName(usrName);
    }

    @Override
    public User login(String usrName, String usrPassword) {
        QueryWrapper<User> qw=new QueryWrapper();
        qw.eq("usr_name",usrName);
        qw.eq("usr_password",usrPassword);
        return userMapper.selectOne(qw);
    }

    @Override
    public IPage<User> getUsersByPage(String usrName, Long roleId, Integer pageNo, Integer pageSize) {
        //组装分页条件
        Page<User> page=new Page<>(pageNo,pageSize);

        //组装过滤条件
        Map<String,Object> param =new HashMap<>();
        param.put("usrName",usrName);
        param.put("roleId",roleId);

        //调用分页方法了
        IPage<User> userIPage=userMapper.getUsersByPage(page,param);
        return userIPage;
    }

    @Override
    public int addUser(User user) {
        user.setUsrPassword(MD5Utils.ssss(user.getUsrPassword()));
        return userMapper.insert(user);
    }
    @Override
    public User selectOne(Long userId){
        User user = userMapper.selectById(userId);
        return user;
    }

    @Override
    public int update(User user) {
        user.setUsrPassword(MD5Utils.ssss(user.getUsrPassword()));
        int rs = userMapper.updateById(user);
        if (rs>0){
            RealmSecurityManager realmSecurityManager = (RealmSecurityManager)SecurityUtils.getSecurityManager();
            MyRealm next = (MyRealm)realmSecurityManager.getRealms().iterator().next();
            next.clearAllCachedAuthorizationInfo();
        }

        return rs;
    }

    @Override
    public int deleteUser(Long id) {
        return userMapper.deleteById(id);
    }


}
